package com.yiren.dbaa.module.practice_set.device;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.yiren.backstage.currency.constant.SignalGConstant;
import com.yiren.dbaa.R;
import com.yiren.dbaa.activity.BaseActivity;
import com.yiren.dbaa.constant.SendParamConstant;
import com.yiren.dbaa.module.device.contract.BlueToothContract;
import com.yiren.dbaa.module.device.presenter.BlueToothPresenter;
import com.yiren.dbaa.view.toast.MessageBox;

import org.apache.commons.lang.StringUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author lwb
 * @date :2021/11/24 14:07
 * @description: 蓝牙工具（手机采集基站标定）
 */
public class BlueToothActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener, BlueToothContract.View {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.sp_blue_tooth)
    Spinner spBlueTooth;
    @BindView(R.id.et_blue_data)
    EditText etBlueData;
    @BindView(R.id.et_out_order)
    EditText etOutOrder;
    @BindView(R.id.cb_change_row)
    CheckBox cbChangeRow;
    @BindView(R.id.cb_hex_data)
    CheckBox cbHexData;

    private SharedPreferences preferences;
    private String btDeviceName;  //蓝牙设备名称
    private boolean isHEX;
    private boolean isRet;        //是否换行
    private Runnable stateInfoRunnable;
    private long lastClickTime;     //上一次点击时间
    private Handler handlers = new Handler();

    private BlueToothContract.Presenter bluetoothPresenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blue_tooth);
        ButterKnife.bind(this);
        initData();
        refresh();
    }

    private void initData() {
        tvTitle.setText("蓝牙工具");
        preferences = getSharedPreferences(SendParamConstant.RTK, 0);
        btDeviceName = preferences.getString(SendParamConstant.BT, "");
        isHEX = preferences.getBoolean(SendParamConstant.HEX, true);
        isRet = preferences.getBoolean(SendParamConstant.RET, false);
        cbChangeRow.setOnCheckedChangeListener(this);
        cbHexData.setOnCheckedChangeListener(this);
        bluetoothPresenter = new BlueToothPresenter(this);
        bluetoothPresenter.getBluetoothSpinner(this);
        refresh();
    }

    @OnClick({R.id.iv_back, R.id.bt_open_blue, R.id.bt_close_blue, R.id.bt_send_order, R.id.bt_send_cjms, R.id.bt_clear_data})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:       //返回
                finish();
                break;
            case R.id.bt_open_blue:  //打开
                if ((System.currentTimeMillis() - lastClickTime) > 5000) { //如果没有快读点击并且蓝牙不是正在打开中的状态
                    lastClickTime = System.currentTimeMillis();
                    bluetoothPresenter.openBluetooth(btDeviceName);
                } else {
                    MessageBox.show(this, "请5秒后再点击！");
                }
                break;
            case R.id.bt_close_blue: //关闭
                bluetoothPresenter.closeBluetooth();
                break;
            case R.id.bt_send_order: //发送
                String order = etOutOrder.getText().toString();
                bluetoothPresenter.sendOrder(order, isHEX, isRet);
                break;
            case R.id.bt_send_cjms:  //CJMS
                //给设备发送---设置采集模式的指令
                bluetoothPresenter.sendOrder("$AT+CJMS\r\n", isHEX, isRet);
                break;
            case R.id.bt_clear_data: //清空显示
                etBlueData.getText().clear();
                break;
        }
    }

    @Override
    public void setBluetoothSpinner(List<String> deviceList) {
        ArrayAdapter<String> deviceNameAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, deviceList);
        deviceNameAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spBlueTooth.setAdapter(deviceNameAdapter);
        spBlueTooth.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                btDeviceName = (String) parent.getAdapter().getItem(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        int index = deviceList.indexOf(btDeviceName);
        if (index != -1) spBlueTooth.setSelection(index);
    }

    private void refresh() {
        stateInfoRunnable = new Runnable() {
            @Override
            public void run() {
                if (etBlueData.getText().toString().length() > 10000) {
                    etBlueData.setText("");
                }
                if (StringUtils.isNotEmpty(SignalGConstant.cfGpsData)) {
                    etBlueData.append(SignalGConstant.cfGpsData + "\n");
                }
                handlers.postDelayed(this, 50);
            }
        };
        stateInfoRunnable.run();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView.getId() == R.id.cb_change_row) {
            isRet = isChecked;
        } else if (buttonView.getId() == R.id.cb_hex_data) {
            isHEX = isChecked;
            etOutOrder.getText().clear();
        }
    }

    @Override
    protected void onDestroy() {
        if (handlers != null && stateInfoRunnable != null) {
            handlers.removeCallbacks(stateInfoRunnable);
        }
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(SendParamConstant.BT, btDeviceName);
        editor.putBoolean(SendParamConstant.HEX, isHEX);
        editor.putBoolean(SendParamConstant.RET, isRet);
        editor.apply();
        super.onDestroy();
    }

}
